<script setup>
import { computed, inject, ref, toRaw, toRefs } from 'vue';
import { storeToRefs } from 'pinia';

import CartCard from '@/components/CartCard.vue';
import userUserCartStore from '@/stores/cart/Cart';
import { routerViewLocationKey, useRoute, useRouter } from "vue-router";
import useUserListStore from "@/stores/user/User.js";
import useOrderStore from "@/stores/order/order.js";
import useCheckedCartStore from "@/stores/cart/CheckedCart.js";
import useUserCartStore from "@/stores/cart/Cart.js"


const UserList = useUserListStore();
const Order = useOrderStore();
const CheckedCart = useCheckedCartStore();
const UserCart = useUserCartStore();


const { cart } = storeToRefs(UserCart);
const { order } = storeToRefs(Order);
const { userList } = storeToRefs(UserList);
const { checkedCart } = storeToRefs(CheckedCart);


// console.log(checkedCart);
// console.log(order);

const route = useRoute();

//                   = userList.value.find(item => {return item.name==="zhangsan"});
const CurrentUserList = userList.value.find(item => item.name === "zhangsan");
const { currentAddress } = toRefs(CurrentUserList)

// 地址是否选择 currentAddress.name!==undefined

// 是否点击提交订单
const isSub = ref(false);

console.log(currentAddress);

// if (route.query.index !== undefined) {
//     // let 不能在if里又突然定义响应式对象
//     currentAddress.value = addressList.value[route.query.index];
// }


// console.log(route.query.index===undefined);
// console.log(route);
console.log(checkedCart);
console.log(cart);

// console.log(cart);
// 当前购物车
const curCart = cart.value.find(item => item.name == route.query.shopName);
// 当前选中购物车
const curChecked = checkedCart.value.find(item => item.name == route.query.shopName);

console.log(curChecked);

// const checkedGoods = computed(()=>{
//     let CartCheckedObj = currentCartObj;
//     // JSON.parse(JSON.stringify(CartChecked));
//     let list =currentCartObj.list.filter(item =>item.checked);

//     CartCheckedObj.list = JSON.parse(JSON.stringify(list));

//    return CartCheckedObj;
// })
// console.log(currentCartObj);
// console.log(checkedGoods.value);
// console.log(curChecked);

//  打印也会触发计算属性 因为打印的计算属性里面调用了其他计算属性
// form: orderconfirm 起源处
const router = useRouter();
const checkAddress = () => {
    router.push({
        name: 'address', //为了地址返回到正确页面 到订单或到首页
        params: { from: "orderConfirm" },
        query: { shopName: route.query.shopName, id: route.query.id },
    })
}


const cancelOrder = () => {


    if (route.query.from==="order") {
       return router.replace({
        path:"/order"
    })
    }

    isSub.value = false;




    let date = new Date();
    let now = date.getTime();
    console.log(now);

    let deadline = now + 15 * 60 * 1000;

    let waitOrder = JSON.parse(JSON.stringify(curChecked));
    waitOrder.deadline = deadline;
    waitOrder.timer = null;
    order.value.push(waitOrder);

    // alert("请在订单取消前完成支付！")
            
    router.replace({
        path:"/order",
        query:{from:"orderConfirm"}

    })

}



const deSub = () => {

    // 在赋值前删除订单表中待支付的订单 删除deadline
    console.log("route.query.from:", route.query.from);
    if (route.query.from === "order") {
        console.log(order);      //order传来的orderId
        order.value.splice(route.query.orderId, 1)
    }


    let waitOrderNO = JSON.parse(JSON.stringify(curChecked));
    // 不再执行
    waitOrderNO.deadline=false;

    // 给订单实例赋值 非响应式
    order.value.push(waitOrderNO);

    //     console.log(checkedCart);
    // console.log(cart);
    // 对于双向绑定的list只有改变其中的值才有效果
    // checkedCart.value[0].list[0]=JSON.parse(JSON.stringify(checkedCart.value[0].list[0]));
    // console.log(checkedCart);
    // console.log(cart);

    // curCart.list.forEach((item,index) =>{
    //     if (item.checked) {
    //         item.number=0;
    //     }
    // })
    // 

    // 删除购物车中已购买的商品     
    for (let i = 0; i < curCart.list.length; i++) {
        //      购物车有一个未选中的，下标就不一样了，保护了选中购物车的第一个下表的商品，跑不到
        if (curCart.list[i].checked) {
            curCart.list[i].number = 0;
            // 
            // curChecked.list[i].number=0;
            curCart.list.splice(i, 1);
            i--;
        }
    }

    // 删除 选中 购物车中已购买的商品     
    for (let i = 0; i < curChecked.list.length; i++) {
        //      购物车有一个未选中的，下标就不一样了，保护了选中购物车的第一个下表的商品，跑不到
        if (curChecked.list[i].checked) {
            // curCart.list[i].number=0;
            curChecked.list.splice(i, 1);

            // curChecked.list[i].number=0;
            // curCart.list.splice(i,1);
            i--;
        }
    }

    // 删除空购物车
    for (let i = 0; i < cart.value.length; i++) {
        //              不共有
        if (cart.value[i].list.length === 0) {
            cart.value.splice(i, 1)
            i--;
        }
    }

    // 删除空的已选中购物车购物车
    for (let i = 0; i < checkedCart.value.length; i++) {
        //              不共有
        if (checkedCart.value[i].list.length === 0) {
            checkedCart.value.splice(i, 1)
            i--;
        }
    }

    // checkedCart.value[0].list.splice(0,1)

    console.log(checkedCart.value);

    console.log(order.value);

    console.log(cart.value);


    // console.log(order.value);

    // curChecked.list.splice(0,1)
    // router
    // console.log(currentCartObj);

    // console.log(JSON.parse(JSON.stringify(currentCartObj)));
    // let orderTable = JSON.parse(JSON.stringify(currentCartObj));
    // orderTable.list= orderTable.list.filter(item =>item.checked);
    // order.value.push(orderTable);
    //   console.log(toRaw(currentCartObj));
    // order.value.push(toRaw(currentCartObj));

    // order.value=

    // 提交订单后删除cart.list中被选中的商品 
    // for (let i = 0; i < currentCartObj.list.length; i++) {
    //     if (currentCartObj.list[i].checked) {
    //             // number归0
    //             currentCartObj.list[i].number=0;
    //             currentCartObj.list.splice(i,1);
    //             i--;
    //     }
    // }
    // console.log(order);
    router.replace({
        path: "/order",
        // query:{orderConfirm:true}
    })
}

const back = () => {
    console.log(route.query.id);


    //     if (route.query.from === "order") {
    //     router.back();
    //     return
    // }

    if (route.query.from === "cart") {
        router.replace({
            path: "/cart",
        })
    } else   {
        // router.replace({
        //     name: "shop",
        //     params: { id: route.query.id }
        // })
        router.back();

    }


}
</script>

<template>
    <div class="order_confirmation">
        <div class="order_confirmation_header">
            <div class="order_confirmation_header_title">
                <span class="iconfont title_back" @click="back()">&#xe697;</span>
                <div class="title_text">确定订单</div>
            </div>
            <div class="order_confirmation_header_address">
                <div class="address_title">收货地址</div>
                <div class="current_address" @click="checkAddress">
                    <div class="current_address_info" v-if="currentAddress !== null">
                        <div>{{ currentAddress.address_text }}</div>
                        <div>{{ currentAddress.name }} {{ currentAddress.phone }}</div>
                    </div>
                    <div class="current_address_info" v-else>暂无收货地址</div>
                    <div class="iconfont current_address_icon">&#xe697;</div>
                </div>
            </div>
        </div>
        <div class="order_confirmation_content">
            <CartCard :CartItem="curChecked || {}" orderconfirm="OConfirm" />
        </div>
        <div class="order_confirmation_footer">
            <div class="total_price">实付金额: <b>￥{{ curChecked.acount }}</b></div>
            <div class="submit" v-if="currentAddress !== null" @click="isSub = true">提交订单</div>
        </div>
        <!-- 蒙层 -->
        <div class="mask" v-if="isSub">
            <div class="mask_content">
                <div class="mask_content_title">确认要离开收银台?</div>
                <div class="mask_content_desc">请尽快完成支付,否则将被取消</div>
                <div class="mask_content_btn">
                    <div class="btn cancel" @click="cancelOrder">取消订单</div>
                    <div class="btn confirm" @click="deSub">确定支付</div>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
@import "@/style/viriables.scss";

.order_confirmation {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: #eee;

    &_header {
        padding: .18rem;
        height: 1.6rem;
        background-image: linear-gradient(0deg, rgba(0, 145, 255, 0.00) 4%, #0091FF 50%);
        background-size: 100% 1.6rem;
        background-repeat: no-repeat;

        &_title {
            display: flex;
            color: $bgColor;

            .title_back {
                font-size: .22rem;
            }

            .title_text {
                flex: 1;
                text-align: center;
                font-size: .16rem;
            }
        }

        &_address {
            padding: .18rem;
            background-color: $bgColor;
            margin-top: .28rem;
            line-height: .22rem;
            font-size: .16rem;
            color: $content_fontcolor;
            border-radius: .04rem;

            .address_title {
                margin-bottom: .18rem;
            }

            .current_address {
                display: flex;
                justify-content: space-between;

                &_info {
                    div:last-child {
                        font-size: .12rem;
                    }
                }

                &_icon {
                    transform: rotate(180deg);
                    margin-right: .08rem;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                }
            }
        }
    }

    &_content {
        width: 100%;
        position: absolute;
        top: 2rem;
        bottom: .5rem;
        box-sizing: border-box;
        overflow-y: scroll;
    }

    &_footer {
        height: .5rem;
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: $bgColor;
        line-height: .5rem;
        display: flex;

        .total_price {
            flex: 1;
            padding-left: .18rem;
        }

        .submit {
            width: 1rem;
            height: .5rem;
            background-color: $btn-bgColor;
            color: $bgColor;
            text-align: center;
            font-size: .14rem;
        }
    }

    // 蒙层
    .mask {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 999;
        background-color: rgba($color: #000000, $alpha: .5);
        display: flex;
        justify-content: center;
        align-items: center;

        &_content {
            width: 80%;
            padding: .24rem;
            box-sizing: border-box;
            background-color: $bgColor;
            border-radius: .04rem;
            text-align: center;

            &_title {
                font-size: .18rem;
                font-weight: bold;
                color: $content_fontcolor;
            }

            &_desc {
                margin: .12rem 0;
                line-height: .2rem;
                font-size: .14rem;
                color: $medium-fontColor;
            }

            &_btn {
                display: flex;
                justify-content: center;

                .btn {
                    width: .8rem;
                    height: .32rem;
                    border-radius: .24rem;
                    font-size: .14rem;
                    line-height: .32rem;
                }

                .cancel {
                    margin-right: .12rem;
                    border: solid .01rem $btn-bgColor;
                    color: $btn-bgColor;
                }

                .confirm {
                    background-color: $btn-bgColor;
                    color: $bgColor;
                }
            }
        }
    }
}
</style>